package com.example.datastorelearn

import android.app.Application
import android.content.Context
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.AndroidViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

/**
 * @author huangzehui
 * @date 2/6/2024 下午9:58 周日
 * @description
 */
class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val Context.dataStore by preferencesDataStore("my_cache")

//    private val Context.dataStore by preferencesDataStore("my_cache", produceMigrations = {context: Context ->
//        // 从 sp 迁移
//        listOf(SharedPreferencesMigration(context,"sp.pref"))
//    })

    private val KEY_NAME = stringPreferencesKey("name")
    private val KEY_AGE = intPreferencesKey("age")


    suspend fun save(name: String, age: Int) {
        getApplication<Application>().dataStore.edit {
            it[KEY_NAME] = name
            it[KEY_AGE] = age
        }
    }

    fun load(): Flow<UserModel> {
        return getApplication<Application>().dataStore.data.map {
            UserModel(name = it[KEY_NAME] ?: "", age = it[KEY_AGE] ?: 0)
        }
    }
}